import { FormSchema } from '/@/components/Form';
import { isObject, cloneDeep } from 'lodash-es';
export const getSchemas = (nodeCfg: any): FormSchema[] => {
  // const { defaultConfiguration } = nodeCfg.configurationDescriptor.nodeDefinition;
  let list: Array<FormSchema> = [];
  console.log(nodeCfg);
  switch (nodeCfg.clazz) {
    case 'device profile':
      list = [
        {
          field: 'persistAlarmRulesState',
          label: 'Persist state of alarm rules',
          component: 'Checkbox',
          defaultValue: false,
        },
        {
          field: 'fetchAlarmRulesStateOnStart',
          label: 'Fetch state of alarm rules',
          component: 'Checkbox',
          defaultValue: false,
        },
      ];
      break;
    case 'save attributes':
      list = [
        {
          field: 'scope',
          label: '设备属性范围',
          component: 'Select',
          componentProps: {
            allowClear: false,
            options: [
              { label: '客户端属性', value: 'CLIENT_SCOPE' },
              { label: '服务端属性', value: 'SERVER_SCOPE' },
              { label: '共享属性', value: 'SHARED_SCOPE' },
            ],
          },
          required: true,
          defaultValue: 'CLIENT_SCOPE',
        },
        {
          field: 'updateAttributesOnlyOnValueChange',
          label: 'Save attributes only if the value changes',
          component: 'Switch',
          defaultValue: false,
        },
        {
          field: 'sendAttributesUpdatedNotification',
          label: 'Send attributes updated notification',
          component: 'Switch',
          ifShow: ({ model }) => model.scope == 'SERVER_SCOPE' || model.scope == 'SHARED_SCOPE',
          defaultValue: false,
        },
        {
          field: 'notifyDevice',
          label: 'Notify device',
          component: 'Switch',
          ifShow: ({ model }) => model.scope == 'SHARED_SCOPE',
          defaultValue: false,
        },
      ];
      break;
    case 'save timeseries':
      list = [
        {
          field: 'defaultTTL',
          label: '默认TTL',
          component: 'InputNumber',
          componentProps: {
            placeholder: '请输入默认TTL',
          },
        },
        {
          field: 'skipLatestPersistence',
          label: 'Skip latest persistence',
          component: 'Checkbox',
          defaultValue: false,
        },
        {
          field: 'useServerTs',
          label: 'Use server ts',
          component: 'Checkbox',
          defaultValue: false,
        },
      ];
      break;
    case 'script':
      list = [
        {
          field: 'scriptLang',
          label: '',
          component: 'RadioButtonGroup',
          slot: 'scriptLangSlot',
          componentProps: {
            options: [
              {
                label: 'TBEL',
                value: 'TBEL',
              },
              {
                label: 'JavaScript',
                value: 'JS',
              },
            ],
          },
          colProps: {
            span: 24,
          },
          defaultValue: 'TBEL',
        },
        {
          field: 'tbelScript',
          label: '',
          component: 'Input',
          colProps: {
            span: 0,
          },
          defaultValue: 'return {msg: msg, metadata: metadata, msgType: msgType};',
        },
        {
          field: 'jsScript',
          label: '',
          component: 'Input',
          colProps: {
            span: 0,
          },
          defaultValue: 'return {msg: msg, metadata: metadata, msgType: msgType};',
        },
      ];
      break;
    case 'org.thingsboard.rule.engine.filter.TbCheckAlarmStatusNode':
      list = [
        {
          field: 'alarmStatusList',
          label: 'Alarm status',
          component: 'CheckboxGroup',
          componentProps: {
            options: [
              {
                label: '激活未确认',
                value: 'ACTIVE_UNACK',
              },
              {
                label: '激活已确认',
                value: 'ACTIVE_ACK',
              },
              {
                label: '清除未确认',
                value: 'CLEARED_UNACK',
              },
              {
                label: '清除已确认',
                value: 'CLEARED_ACK',
              },
            ],
          },
          required: true,
        },
      ];
      break;
    case 'org.thingsboard.rule.engine.filter.TbCheckMessageNode':
      list = [
        {
          field: 'messageNames',
          label: 'Message field names',
          component: 'Select',
          componentProps: {
            placeholder: '请输入Message field names',
            mode: 'tags',
            open: false,
          },
        },
        {
          field: 'metadataNames',
          label: 'Metadata field names',
          component: 'Select',
          componentProps: {
            placeholder: '请输入Metadata field names',
            mode: 'tags',
            open: false,
          },
        },
        {
          field: 'checkAllKeys',
          label: 'Check that all specified fields are present',
          component: 'Switch',
        },
      ];
      break;
    case 'org.thingsboard.rule.engine.filter.TbCheckRelationNode':
      list = [
        {
          field: 'direction',
          label: '方向',
          component: 'Select',
          componentProps: {
            options: [
              {
                label: '从originator',
                value: 'FROM',
              },
              {
                label: '到originator',
                value: 'TO',
              },
            ],
          },
          required: true,
        },
        {
          field: 'relationType',
          label: '关系类型',
          component: 'Select',
          componentProps: {
            options: [
              {
                label: 'Contains',
                value: 'Contains',
              },
              {
                label: 'Manages',
                value: 'Manages',
              },
            ],
          },
          required: true,
        },
        {
          field: 'checkForSingleEntity',
          label: 'Check relation to specific entity',
          component: 'Switch',
          defaultValue: false,
        },
        {
          field: 'entityType',
          label: '实体类型',
          component: 'Select',
          componentProps: ({ formActionType }) => {
            return {
              placeholder: '请选择实体类型',
              options: [
                {
                  label: '资产',
                  value: 'ASSET',
                },
                {
                  label: '设备',
                  value: 'DEVICE',
                },
                {
                  label: '用户',
                  value: 'USER',
                },
              ],
              onChange: (value: string) => {
                const { updateSchema } = formActionType;
                let label = '';
                switch (value) {
                  case 'ASSET':
                    label = '资产';
                    break;
                  case 'DEVICE':
                    label = '设备';
                    break;
                  case 'USER':
                    label = '用户';
                    break;
                }
                console.log(label);
                updateSchema({
                  field: 'entityId',
                  label,
                  componentProps: {
                    placeholder: `请选择${label}`,
                  },
                });
              },
            };
          },
          ifShow: ({ values }) => values.checkForSingleEntity,
        },
        {
          field: 'entityId',
          label: '设备',
          component: 'ApiSelect',
          ifShow: ({ values }) => values.checkForSingleEntity && values.entityType,
        },
      ];
      break;
    case 'org.thingsboard.rule.engine.filter.TbOriginatorTypeFilterNode':
      list = [
        {
          field: 'originatorTypes',
          label: '实体类型',
          component: 'Select',
          componentProps: {
            placeholder: '请选择实体类型',
            maxTagCount: 'responsive',
            mode: 'tags',
            options: [
              {
                label: '设备',
                value: 'DEVICE',
              },
              {
                label: '资产',
                value: 'ASSET',
              },
              {
                label: '用户',
                value: 'USER',
              },
            ],
          },
          required: true,
          defaultValue: 'DEVICE',
        },
      ];
      break;
    case 'org.thingsboard.rule.engine.filter.TbMsgTypeFilterNode':
      list = [
        {
          field: 'messageTypes',
          label: '消息类型',
          component: 'Select',
          componentProps: {
            placeholder: '请选择消息类型',
            mode: 'multiple',
            listHeight: 120,
            maxTagCount: 'responsive',
            options: [
              { label: 'POST_ATTRIBUTES_REQUEST', value: 'POST_ATTRIBUTES_REQUEST' },
              { label: 'POST_TELEMETRY_REQUEST', value: 'POST_TELEMETRY_REQUEST' },
              { label: 'TO_SERVER_RPC_REQUEST', value: 'TO_SERVER_RPC_REQUEST' },
              { label: 'RPC_CALL_FROM_SERVER_TO_DEVICE', value: 'RPC_CALL_FROM_SERVER_TO_DEVICE' },
              { label: 'RPC_QUEUED', value: 'RPC_QUEUED' },
              { label: 'RPC_SENT', value: 'RPC_SENT' },
              { label: 'RPC_DELIVERED', value: 'RPC_DELIVERED' },
              { label: 'RPC_SUCCESSFUL', value: 'RPC_SUCCESSFUL' },
              { label: 'RPC_TIMEOUT', value: 'RPC_TIMEOUT' },
              { label: 'RPC_EXPIRED', value: 'RPC_EXPIRED' },
              { label: 'RPC_FAILED', value: 'RPC_FAILED' },
              { label: 'RPC_DELETED', value: 'RPC_DELETED' },
              { label: 'ACTIVITY_EVENT', value: 'ACTIVITY_EVENT' },
              { label: 'INACTIVITY_EVENT', value: 'INACTIVITY_EVENT' },
              { label: 'CONNECT_EVENT', value: 'CONNECT_EVENT' },
              { label: 'DISCONNECT_EVENT', value: 'DISCONNECT_EVENT' },
              { label: 'ENTITY_CREATED', value: 'ENTITY_CREATED' },
              { label: 'ENTITY_UPDATED', value: 'ENTITY_UPDATED' },
              { label: 'ENTITY_DELETED', value: 'ENTITY_DELETED' },
              { label: 'ENTITY_ASSIGNED', value: 'ENTITY_ASSIGNED' },
              { label: 'ENTITY_UNASSIGNED', value: 'ENTITY_UNASSIGNED' },
              { label: 'ATTRIBUTES_UPDATED', value: 'ATTRIBUTES_UPDATED' },
              { label: 'ATTRIBUTES_DELETED', value: 'ATTRIBUTES_DELETED' },
              { label: 'ALARM_ACKNOWLEDGED', value: 'ALARM_ACKNOWLEDGED' },
              { label: 'ALARM_CLEARED', value: 'ALARM_CLEARED' },
              { label: 'ALARM_ASSIGNED', value: 'ALARM_ASSIGNED' },
              { label: 'ALARM_UNASSIGNED', value: 'ALARM_UNASSIGNED' },
              { label: 'COMMENT_CREATED', value: 'COMMENT_CREATED' },
              { label: 'COMMENT_UPDATED', value: 'COMMENT_UPDATED' },
              { label: 'ENTITY_ASSIGNED_FROM_TENANT', value: 'ENTITY_ASSIGNED_FROM_TENANT' },
              { label: 'ENTITY_ASSIGNED_TO_TENANT', value: 'ENTITY_ASSIGNED_TO_TENANT' },
              { label: 'TIMESERIES_UPDATED', value: 'TIMESERIES_UPDATED' },
              { label: 'TIMESERIES_DELETED', value: 'TIMESERIES_DELETED' },
            ],
          },
        },
      ];
      break;
  }

  list.push({
    field: 'description',
    label: '描述',
    component: 'InputTextArea',
    componentProps: {
      placeholder: '请输入描述',
    },
    colProps: {
      span: 24,
    },
    defaultValue: '',
  });
  return [
    {
      field: 'name',
      label: '名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入名称',
      },
      required: true,
    },
    {
      field: 'debugMode',
      label: '调试模式',
      component: 'Switch',
      defaultValue: false,
    },
    ...list,
  ];
};

export const getNodeData = (data, descriptor, EntityType, nodeId, ruleChainId, isNewNode) => {
  const obj = {
    ...data,
    singletonMode: false,
    type: descriptor.value?.clazz || '',
    configuration:
      descriptor.value?.configurationDescriptor.nodeDefinition.defaultConfiguration || {},
    additionalInfo: { description: '', layoutX: 0, layoutY: 0 },
    id: { entityType: EntityType.RULE_NODE, id: nodeId.value },
    ruleChainId: ruleChainId.value,
    configurationVersion: descriptor.value?.configurationVersion || 0,
    createdTime: descriptor.value?.createdTime || new Date().getTime(),
    isNewNode: isNewNode.value,
  };
  return obj;
};

export const recursion = (data) => {
  let obj = {};
  const res = cloneDeep(data);
  Object.keys(res).forEach((key) => {
    if (isObject(res[key])) {
      obj = { ...obj, ...res[key] };
      recursion(res[key]);
    } else {
      obj[key] = res[key];
    }
  });

  return obj;
};

export const processingData = (key: string, data: any, descriptor?: any) => {
  const { name } = descriptor;
  if (key == 'display') {
    switch (name) {
      case 'script':
        return {
          name: data.name,
          debugMode: data.debugMode,
          description: data.description,
          transformScript: {
            scriptLang: data.scriptLang,
            jsScript: data.jsScript,
            tbelScript: data.tbelScript,
          },
        };
      default:
        return data;
    }
  } else if (key == 'save') {
    switch (name) {
      case 'script':
        return recursion(data);
      default:
        return data;
    }
  }
};
